//
//  SetAlarmViewController.m
//  JiuLe
//
//  Created by xcq on 15/11/10.
//  Copyright © 2015年 Fine. All rights reserved.
//

#import "PopView.h"
#import "Common.h"
#import "SocketManager.h"
#import "SetAlarmViewController.h"
#define kEventTag 0x1FF
#define kHourTag 0x2FF
#define kMinuteTag 0x3FF
@interface SetAlarmViewController () <UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *eventDetail;
@property (weak, nonatomic) IBOutlet UITextField *hourDetail;
@property (weak, nonatomic) IBOutlet UITextField *minuteDetail;
@property (weak, nonatomic) IBOutlet UIButton *RemindType;
@property (weak, nonatomic) IBOutlet UIView *firstView;
@property (weak, nonatomic) IBOutlet UIView *secondView;
@property (copy, nonatomic) NSString *remind_type;

@end

@implementation SetAlarmViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"设置闹钟";
    [self showNavBarWithRightTitle:nil
                    andRightAction:nil
                     andLeftAction:nil
                 andRightBtnIsShow:NO];
    [self setUpAlarmDetail];
}

- (void)setUpAlarmDetail {

    _eventDetail.tag = kEventTag;
    _hourDetail.tag = kHourTag;
    _minuteDetail.tag = kMinuteTag;
   
//    if ([_model.remind_type integerValue] == 1) {
//        [_RemindType setTitle:@"响铃" forState:UIControlStateNormal];
//    } else if ([_model.remind_type integerValue] == 2){
//        [_RemindType setTitle:@"震动" forState:UIControlStateNormal];
////        _eventDetail.text = @"震动";
//    } else if ([_model.remind_type integerValue] == 3){
//        [_RemindType setTitle:@"响铃+震动" forState:UIControlStateNormal];
////        _eventDetail.text = @"响铃+震动";
//    }
        [_RemindType setTitle:@"震动" forState:UIControlStateNormal];
    if ([_model.type integerValue] == 1) {
         _eventDetail.text = @"跑步";
    } else if ([_model.type integerValue] == 2) {
        _eventDetail.text = @"吃药";
    } else {
        _eventDetail.text = @"睡觉";
    }
    
    _hourDetail.text = [_model.clock substringWithRange:NSMakeRange(0, 2)];
    _minuteDetail.text = [_model.clock substringWithRange:NSMakeRange(2, 2)];
}

- (IBAction)remindEvent:(id)sender {
    [self.view endEditing:YES];
//    PopView *view = [[[NSBundle mainBundle] loadNibNamed:@"PopView" owner:self options:nil] lastObject];
//    view.frame = (CGRect)CGRectMake(CGRectGetWidth(self.view.frame)/2 - (CGRectGetWidth(view.frame) / 2), CGRectGetHeight(self.view.frame)/2 - (CGRectGetHeight(view.frame) / 2), CGRectGetWidth(view.frame), CGRectGetHeight(view.frame));
//    [self.view addSubview:view];
//    [view viewDidLoad:[_model.remind_type intValue]];
//    view.action = ^(NSString *str) {
//        [_RemindType setTitle:str forState:UIControlStateNormal];
//        if ([str isEqualToString:@"响铃"]) {
//            _remind_type = @"1";
//        } else if ([str isEqualToString:@"闹钟"]) {
//            _remind_type = @"2";
//        } else {
//            _remind_type = @"3";
//        }
//    };
}

- (IBAction)saveSetting:(id)sender {
    [self.view endEditing:YES];
    if (![SocketManager sharedInstance].socket.isConnected) {
        [SVProgressHUD showErrorWithStatus:@"当前未连接到久乐表，无法保存数据"];
        return;
    }
    _model.clock = [_hourDetail.text stringByAppendingString:_minuteDetail.text];
 
    _model.remind_type = @"3";
    _model.is_set = @"1";
    
    if ([_model.type integerValue] == 1) {
        [NSUserDefaults setUserObject:_model forKey:UserDataAlarmArraysOne];
        [[NSUserDefaults standardUserDefaults] setObject:_model.type forKey:UserDataAlarmChangeOne];
    } else if ([_model.type integerValue] == 2) {
        [NSUserDefaults setUserObject:_model forKey:UserDataAlarmArraysTwo];
        [[NSUserDefaults standardUserDefaults] setObject:_model.type forKey:UserDataAlarmChangeTwo];
    } else if ([_model.type integerValue] == 3) {
        [NSUserDefaults setUserObject:_model forKey:UserDataAlarmArraysThree];
        [[NSUserDefaults standardUserDefaults] setObject:_model.type forKey:UserDataAlarmChangeThree];
    }
    
    [SVProgressHUD showWithStatus:@""];
    NSMutableArray *arr = [NSMutableArray new];
    
    JLClockModel *dic1 = [NSUserDefaults objectUserForKey:UserDataAlarmArraysOne];
    JLClockModel *dic2 = [NSUserDefaults objectUserForKey:UserDataAlarmArraysTwo];
    JLClockModel *dic3 = [NSUserDefaults objectUserForKey:UserDataAlarmArraysThree];
//    
    NSArray *arrTemp = @[dic1,dic2,dic3];
    for (int i = 0; i < arrTemp.count; i ++) {
        JLClockModel *dic = arrTemp[i];
        if (dic!=nil && dic.clock!=nil) {
            [arr addObject:[[[dic.clock substringWithRange:NSMakeRange(0, 2)] stringByAppendingString:@":"] stringByAppendingString:[dic.clock substringWithRange:NSMakeRange(2, 2)]]];
        }
    }
    [[SocketManager sharedInstance] writeAlarmClock:arr];
    _weakAlarm.isChange = YES;
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

- (NSTimeInterval)DateStrConvertSince1970:(NSString *)dateStr {
    NSDateFormatter *fomatter = [[NSDateFormatter alloc] init];
    [fomatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    NSDate *curren = [NSDate date];
    NSString *currenStr = [fomatter stringFromDate:curren];
    currenStr = [currenStr stringByReplacingCharactersInRange:NSMakeRange(11, 5) withString:dateStr];
    NSDate *date = [fomatter dateFromString:currenStr];
    return [date timeIntervalSince1970];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    if (textField.tag == kEventTag) {
        if (![Common verificationNickName:toBeString]) {
            return NO;
        }
        //TODO:长度限制
        if (toBeString.length > 6) {
            return NO;
        }
    } else  {
        NSCharacterSet *cs;
        cs = [[NSCharacterSet characterSetWithCharactersInString:kNumbers] invertedSet];
        NSString *filtered =
        [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
        if (![string isEqualToString:filtered]) {
            return NO;
        }
        if (textField.tag == kHourTag) {
            if (toBeString.length > 2) {
                return NO;
            }
            if ([toBeString intValue] > 23 || [toBeString intValue] < 0) {
                return NO;
            }
        } else {
            if (toBeString.length > 2) {
                return NO;
            }
            
            if (toBeString.intValue > 59 || toBeString.intValue < 0) {
                return NO;
            }
        }
    }
    return YES;
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
    if (textField.text.length == 1) {
        textField.text = [@"0" stringByAppendingString:textField.text];
    }
    
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
